import { Button, Flex, GetProps, Input, Popconfirm, Space, Table } from "antd";
import { useEffect, useRef, useState,memo } from "react";
import { Role, roleDelete, roleList } from "./roleApi";
import { FilterDTO } from "@/utils/api/interface";
import FormDrawer from "./form";
import { getPage, initFilter } from "@/config/page";
import ConfirmButton from "@/components/Button/ConfirmButton";
import { deleteById, updateById } from "@/utils/util";
import TablePro from "@/components/TablePro";
import AuthButton from "@/routers/utils/authButton";
import { useTranslation } from "react-i18next";
type SearchProps = GetProps<typeof Input.Search>;

const { Search } = Input;

const RolePage = memo(() => {
	const { t } = useTranslation();
	const [data, setData] = useState<Role.RoleDTO[]>([]);
	const [total, setTotal] = useState<number>(0);
	const [filter, setFilter] = useState<FilterDTO>(initFilter);
	const formRef: any = useRef();
	const resetRef: any = useRef();

	useEffect(() => {
		(async () => {
			const res = await roleList(filter);
			setData(res.data || []);
			setTotal(res.total);
		})();
	}, [filter]);
	const edit = async (id: string) => {
		formRef.current.open(id);
	};
	const del = async (id: string) => {
		const res = await roleDelete(id);
		if (res.code == 0) {
			setData(deleteById(data, "roleId", id));
		}
	};

	const columns: any[] = [
		{
			title: t("role.roleName"),
			dataIndex: "roleName",
			key: "roleName",
			align: "left",
		},
		{
			title: t("note"),
			dataIndex: "note",
			key: "note",
			align: "left",
		},
		{
			title: t("action"),
			width: 160,
			dataIndex: "roleId",
			key: "roleId",
			align: "center",
			render: (val: string, record: Role.RoleDTO) => {
				if (record.isSys) {
					return <></>
				} else {
					return <Space size="middle">
						<AuthButton permission="role:edit"><Button type="link" onClick={() => edit(val)}>{t("edit")}</Button></AuthButton>
						<AuthButton permission="role:edit"><ConfirmButton title={t("role.delete")} onConfirm={() => del(val)} /></AuthButton>
					</Space>
				}
			},
		},
	];
	const onSearch: SearchProps["onSearch"] = (value, _e, info) => {
		setFilter({ ...filter, keyword: value });
	};

	const onUpdate = (val: Role.RoleDTO) => {
		setData(updateById(data, "roleId", val));
	};

	return (
		<div className="card content-box">
			<Flex className="head-line" justify="space-between">
				<Space>
					<Search placeholder={t("pik")} allowClear onSearch={onSearch} style={{ width: 400 }} />
				</Space>
				<Space>
					<AuthButton permission="role:edit">
						<Button type="primary" onClick={() => formRef.current.open("")}>
							{t("role.add")}
						</Button>
					</AuthButton>
				</Space>
			</Flex>
			<TablePro
				bordered={true}
				dataSource={data}
				columns={columns}
				pagination={getPage(total, (val) => setFilter({ ...filter, ...val }))}
			/>

			<FormDrawer update={onUpdate} ref={formRef} />
		</div>
	);
});

export default RolePage;
